package com.uenpay.im.ui.old.activity.funds;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.base.BaseActivity;
import com.uenpay.im.ui.old.activity.pwd.SetPayPwdActivity;
import com.uenpay.im.ui.old.activity.wallet.ChargeActivity;
import com.uenpay.im.ui.old.activity.wallet.WalletHandle;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.weight.BottomDialog;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.im.weight.PayPwdDialog;
import com.uenpay.im.weight.relationlistview.ExpandListAdapter;
import com.uenpay.im.weight.relationlistview.RelationListView;

import java.util.ArrayList;

/**
 * @author SL
 * @copyRight http://www.qiyunxin.com
 * @E-mail:
 * @date 创建时间：2016-5-9 下午4:54:51
 * @version 1.0
 * @function 经费管理
 */
public class FundsManageActivity extends BaseActivity {

	private TextView group_funds_tv;
	private TextView cost_tv, income_tv;
	/**
	 * 选中类型1为收入，2为支出
	 */
	private int selectedType = 2;
	private Button add_btn;
	private String chat_id = "";
	private FundsCostAdapter mFundsCostAdapter;
	// private FundsRevenueAdapter mFundsRevenueAdapter;
	private RelativeLayout classmate_group_head;
	private ExpandListAdapter expandListAdapter;
	private RelationListView relationListView;
	private ListView listview;
	private ArrayList<FundsInEntity> arrayList;
	private double myBalance;
	private int haspaypassword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		IMApplication.getInstance().addActivity(this);
		setContentView(R.layout.activity_funds_manage_layout);
		chat_id = getIntent().getStringExtra("chat_id");
		if (getIntent().hasExtra("selected_type")) {
			selectedType = getIntent().getIntExtra("selected_type", 2);
		}
		initView();
		backListener();
		initListener();
		getMyBalance();
		// getFundsList();
		getGroupFunds();
	}

	@Override
	protected void initView() {
		group_funds_tv = (TextView) findViewById(R.id.group_funds_tv);
		((TextView) findViewById(R.id.title_textview))
				.setText(R.string.funds_manager);
		((ImageView) findViewById(R.id.title_right_add_iv))
				.setImageResource(R.drawable.icon_more1);
		cost_tv = (TextView) findViewById(R.id.cost_tv);
		income_tv = (TextView) findViewById(R.id.income_tv);
		add_btn = (Button) findViewById(R.id.add_btn);
		loading = findViewById(R.id.loading);
		listview = (ListView) findViewById(R.id.listview);
		relationListView = (RelationListView) findViewById(R.id.income_listview);
		updateSelectedType(selectedType);

		classmate_group_head = (RelativeLayout) this.getLayoutInflater()
				.inflate(R.layout.item_funds_group_header,
						relationListView, false);
		relationListView.setHeaderView(classmate_group_head);
		relationListView.setGroupIndicator(null);

	}

	@Override
	protected void initListener() {

		relationListView.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				if (expandListAdapter.getGroupClickStatus(groupPosition) == 0) {
					expandListAdapter.setGroupClickStatus(groupPosition, 1);
					parent.expandGroup(groupPosition);
					parent.setSelectedGroup(groupPosition);

				} else
					if (expandListAdapter.getGroupClickStatus(groupPosition) == 1) {
					expandListAdapter.setGroupClickStatus(groupPosition, 0);
					parent.collapseGroup(groupPosition);
				}
				updateList(groupPosition);

				return true;
			}
		});

		relationListView.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				FundsInDetailEntity detailEntity = arrayList.get(groupPosition).arrayList
						.get(childPosition);
				if (detailEntity != null
						&& detailEntity.status == 0
						&& detailEntity.custid.equals(IMApplication
								.getCustId())) {
					if (!TextUtils.isEmpty(detailEntity.amount)) {
						double temp = Double.valueOf(detailEntity.amount);
						if (temp > myBalance) {
							showInsufficientBalanceDialog();
						} else {
							if (haspaypassword == 1) {
								showPayPwdDialog(detailEntity.contributid + "");
							} else {
								showSetPwdDialog();
							}
						}
					}
				}
				return false;
			}
		});

		findViewById(R.id.title_right_iv_layout).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						updateJoinGroupAmountDialog();
					}
				});
		cost_tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (!isGet) {
					updateSelectedType(2);
				}
			}
		});
		income_tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (!isGet) {
					updateSelectedType(1);
				}
			}
		});

		add_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.putExtra("chat_id", chat_id);
				if (selectedType == 2) {
					intent.setClass(FundsManageActivity.this,
							RecordFundsActivity.class);
				} else {
					intent.setClass(FundsManageActivity.this,
							ReceiveFundsActivity.class);
				}
				startActivityForResult(intent, 100);
			}
		});

		// income_listview.setOnItemClickListener(new OnItemClickListener() {
		//
		// @Override
		// public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
		// long arg3) {
		// FundsInEntity fundsInEntity = (FundsInEntity) arg0.getAdapter()
		// .getItem(arg2);
		// if (fundsInEntity != null) {
		// Intent intent = new Intent(FundsManageActivity.this,
		// FundsIncomeListActivity.class);
		// intent.putExtra("arraylist", fundsInEntity.msg_list);
		// intent.putExtra("pay_amount", fundsInEntity.amount);
		// startActivityForResult(intent, 100);
		// }
		// }
		// });
		listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				FundsOutEntity mFundsOutEntity = (FundsOutEntity) arg0
						.getAdapter().getItem(arg2);
				if (mFundsOutEntity != null) {
					showDetailFundsDailog(mFundsOutEntity.id);
				}
				return false;
			}
		});
	}



	/**
	 * 支付密码提示框
	 *
	 * @param contributid
	 */
	private void showPayPwdDialog(final String contributid) {
		PayPwdDialog.showBottomRedDialog(FundsManageActivity.this,
				new PayPwdDialog.IPayPwdInputFinishListener() {

					@Override
					public void onPayPwdInputFinish(String payPwd) {
						doContributToGroupFunds(contributid, payPwd);
					}
				});
	}


	private void doContributToGroupFunds(String contributid, String paypassword) {
		loading.setVisibility(View.VISIBLE);
		FundsHandle.doContributToGroupFunds(contributid, paypassword,
				new FundsHandle.IFundsListener() {

					@Override
					public void onFundsResult(int status, String msg) {
						loading.setVisibility(View.GONE);
						if (status == HttpInvokeResultCode.RESULT_OK) {
							setResult(RESULT_OK);
							finish();
						} else if (status == 2605) {
							showInsufficientBalanceDialog();
						}else if(!TextUtils.isEmpty(msg)){
							IMApplication.showToast(msg);
						}
					}
				});
	}

	private void getMyBalance() {
		WalletHandle.getBalance(new WalletHandle.IGetBalanceResultListener() {

			@Override
			public void onGetBalanceResult(String balance, int status,
										   int _haspaypassword) {
				if (status == HttpInvokeResultCode.RESULT_OK) {
					if (!TextUtils.isEmpty(balance)) {
						myBalance = Double.valueOf(balance);
					}
					haspaypassword = _haspaypassword;
				}
			}
		});
	}
	/**
	 * 余额不足提示
	 */
	private void showInsufficientBalanceDialog() {
		loading.setVisibility(View.GONE);
		DialogUtility.showDialog(FundsManageActivity.this,
				R.string.insufficient_balance, R.string.sure, R.string.cancel,
				true, new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						Intent intent = new Intent(
								FundsManageActivity.this,
								ChargeActivity.class);
						startActivityForResult(intent, 100);
					}
				});
	}

	/**
	 * 设置支付密码对话框
	 */
	private void showSetPwdDialog() {
		DialogUtility.showDialog(FundsManageActivity.this,
				R.string.not_set_pay_pwd, R.string.sure, R.string.cancel, true,
				new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						Intent intent = new Intent(
								FundsManageActivity.this,
								SetPayPwdActivity.class);
						startActivity(intent);
						finish();
					}
				});
	}


	private void showDetailFundsDailog(final int id) {
		DialogUtility.showDialog(FundsManageActivity.this,
				R.string.delete_funds_cost, R.string.sure, R.string.cancel,
				true, new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						deleteFundsCost(id);
					}
				});
	}

	private void deleteFundsCost(int id) {
		FundsHandle.deleteFundsCost(id, chat_id, new FundsHandle.IFundsListener() {

			@Override
			public void onFundsResult(int status, String msg) {
				if (status == HttpInvokeResultCode.RESULT_OK) {
					getGroupFunds();
					updateSelectedType(selectedType);
				}
			}
		});
	}

	private boolean isGet = false;

	private void updateSelectedType(int type) {
		selectedType = type;
		if (type == 2) {
			cost_tv.setBackgroundResource(R.color.the_color_black);
			cost_tv.setTextColor(getResources().getColor(
					R.color.the_color_white));
			income_tv.setBackgroundResource(R.color.transparent);
			income_tv.setTextColor(getResources().getColor(
					R.color.the_color_black));
			add_btn.setText(R.string.add_funds);
		} else {
			income_tv
					.setBackgroundResource(R.color.the_color_black);
			income_tv.setTextColor(getResources().getColor(
					R.color.the_color_white));
			cost_tv.setBackgroundResource(R.color.transparent);
			cost_tv.setTextColor(getResources().getColor(
					R.color.the_color_black));
			add_btn.setText(R.string.received_funds);
		}
		if (selectedType == 1) {
			getGroupFundsIncome();
		} else {
			getFundsList();
		}
	}

	private void updateJoinGroupAmountDialog() {
		BottomDialog.showBottomDialog(FundsManageActivity.this, getResources()
						.getString(R.string.update_join_group_amount), "",
				getResources().getString(R.string.cancel), -1,
				new IOnBottomDialogListener() {

					@Override
					public void onClicked() {
						Intent intent = new Intent(FundsManageActivity.this,
								UpdateJoinGroupAmountActivity.class);
						intent.putExtra("chat_id", chat_id);
						startActivity(intent);
					}
				}, null);
	}

	private void getGroupFunds() {
		isGet = true;
		loading.setVisibility(View.VISIBLE);
		FundsHandle.getChatFundsAmount(chat_id, new FundsHandle.IGetChatFundsAmount() {

			@Override
			public void onGetFundsAmount(
					GetFundsChatAmountInvokeItem.GetFundsChatAmountInvokeItemResult result) {
				myHandler.sendEmptyMessage(0);
				if (result != null) {
					if (result.status == HttpInvokeResultCode.RESULT_OK) {
						if (result._isadmin == 1
								&& result.custid.equals(IMApplication
										.getCustId())) {
							add_btn.setVisibility(View.VISIBLE);
							findViewById(R.id.title_right_iv_layout)
									.setVisibility(View.VISIBLE);
						} else {
							findViewById(R.id.title_right_iv_layout)
									.setVisibility(View.GONE);
							add_btn.setVisibility(View.GONE);
						}
						group_funds_tv.setText(result.leftAmount + "");
					} else if (TextUtils.isEmpty(result.msg)) {
						IMApplication.showToast(result.msg);
					}
				}
			}
		});
	}

	private void getGroupFundsIncome() {
		isGet = true;
		loading.setVisibility(View.VISIBLE);
		FundsHandle.getFundsRevenueList(chat_id,
				new FundsHandle.IGetFundsRevenueListener() {

					@Override
					public void onGetFundsRevenueResult(
							GetChatRevenueListInvokeItem.GetChatRevenueListInvokeItemResult result) {
						isGet = false;
						myHandler.sendEmptyMessage(0);
						if (result != null
								&& result.status == HttpInvokeResultCode.RESULT_OK) {
							// mFundsRevenueAdapter = new FundsRevenueAdapter(
							// FundsManageActivity.this, result.msg_list);
							// income_listview.setAdapter(mFundsRevenueAdapter);
							// income_listview.setVisibility(View.VISIBLE);
							// listview.setVisibility(View.GONE);
							arrayList = result.arrayList;
							expandListAdapter = new ExpandListAdapter(
									FundsManageActivity.this, relationListView);
							expandListAdapter.setData(result.arrayList);
							relationListView.setAdapter(expandListAdapter);
							relationListView.setVisibility(View.VISIBLE);
							listview.setVisibility(View.GONE);
							relationListView.setSelectedGroup(0);
							for (int i = 0; i < expandListAdapter
									.getGroupCount(); i++) {
								relationListView.collapseGroup(i);
								expandListAdapter.setGroupClickStatus(i, 0);
							}
						}
					}
				});
	}


	private void updateList(int groupPosition) {
		for (int i = 0; i < expandListAdapter.getGroupCount(); i++) {
			if(groupPosition == i){
				continue;
			}else{
				relationListView.collapseGroup(i);
				expandListAdapter.setGroupClickStatus(i, 0);
			}
		}
		expandListAdapter.notifyDataSetChanged();
	}

	private Handler myHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message arg0) {
			if (arg0.what == 0) {
				if (loading != null)
					loading.setVisibility(View.GONE);
			}
			return false;
		}
	});

	private void getFundsList() {
		isGet = true;
		loading.setVisibility(View.VISIBLE);
		FundsHandle.getFundsList(chat_id, selectedType,
				new FundsHandle.IGetFundsListListener() {

					@Override
					public void onGetFundsResult(int status, String msg,
							ArrayList<FundsOutEntity> arrayList) {
						isGet = false;
						myHandler.sendEmptyMessage(0);
						mFundsCostAdapter = new FundsCostAdapter(
								FundsManageActivity.this, arrayList);
						listview.setAdapter(mFundsCostAdapter);
						relationListView.setVisibility(View.GONE);
						listview.setVisibility(View.VISIBLE);
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 100 && resultCode == RESULT_OK) {
			getGroupFunds();
			updateSelectedType(selectedType);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onBackPressed() {
		finish();
		super.onBackPressed();
	}

	@Override
	protected void onDestroy() {
		IMApplication.getInstance().removeActivity(this);
		super.onDestroy();
	}

}
